package com.campus.service.impl;

import com.campus.service.UserService;
import com.campus.dao.UserDao;
import com.campus.model.User;
import com.campus.utils.JwtUtils;
import com.campus.exception.UserNotFoundException;
import com.campus.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {

    private  UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User updateUser(Long id, User user) {
        User existingUser = userDao.queryUser(String.valueOf(id)).stream().findFirst().orElse(null);
        if (existingUser == null) {
            throw new UserNotFoundException("用户不存在，无法更新");
        }
        BeanUtils.copyProperties(user, existingUser, "id");
        if (userDao.updateUser(existingUser) > 0) {
            return existingUser;
        }
        throw new RuntimeException("更新用户失败");
    }

    @Override
    public User getUserById(Long id) {
        return userDao.queryUser(String.valueOf(id)).stream()
                .findFirst()
                .orElseThrow(() -> new UserNotFoundException("根据ID未找到用户：" + id));
    }

    @Override
    public User getUserByUsername(String username) {
        return userDao.queryUser(username).stream()
                .findFirst()
                .orElseThrow(() -> new UserNotFoundException("未找到用户名为：" + username + " 的用户"));
    }

    @Override
    public String login(String loginName, String password) {
        User user = userDao.login(loginName, password);
        if (user == null || !password.equals(user.getPassword())) {
            throw new UserNotFoundException("用户名或密码错误");
        }
        return JwtUtils.generateToken(user.getLoginName()); }


    @Override
    public User createUser(User user) {
        if (userDao.addUser(user) > 0) {
            return user;
        }
        throw new RuntimeException("创建用户失败");
    }


}
